package com.artron.mediaartron.ui.fragment.center;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.artron.baselib.base.BaseStaticFragment;
import com.artron.baselib.entity.Response;
import com.artron.baselib.utils.ToastUtil;
import com.artron.mediaartron.R;
import com.artron.mediaartron.data.config.AppProfile;
import com.artron.mediaartron.data.entity.User;
import com.artron.mediaartron.data.net.RetrofitHelper;
import com.artron.mediaartron.data.net.api.LoginApi;
import com.artron.mediaartron.util.RegexUtils;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import rx.functions.Action1;

/**
 * 更换手机号
 * Created by qi on 2017/11/27.
 */

public class AlterationPhoneFragment extends BaseStaticFragment implements View.OnClickListener {

    public static final String CHANGE_PHONE = "ChangePhone";
    @BindView(R.id.AlterationPhoneFragment_et_phone)
    protected EditText mEtPhone;
    @BindView(R.id.AlterationPhoneFragment_etCode)
    protected EditText mEtCode;
    @BindView(R.id.AlterationPhoneFragment_tv_sendCode)
    protected TextView mTvSendCode;
    @BindView(R.id.AlterationPhoneFragment_btn_ensure)
    protected Button mBtnEnsure;

    private int mCaptchaSecond = 0;
    private boolean isCanClickCaptcha = true;
    private Timer mTimer;


    public static AlterationPhoneFragment newInstance() {

        Bundle args = new Bundle();
        AlterationPhoneFragment fragment = new AlterationPhoneFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_alteration_phone;
    }

    @Override
    protected void initView() {
        mBtnEnsure.setOnClickListener(this);
        mTvSendCode.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        String phoneNumber = mEtPhone.getText().toString().trim();
        String verificationCode = mEtCode.getText().toString().trim();
        switch (view.getId()) {
            case R.id.AlterationPhoneFragment_tv_sendCode://发送验证码
                sendVerificationCode(phoneNumber);
                break;
            case R.id.AlterationPhoneFragment_btn_ensure://确认修改
                confirmationModification(phoneNumber, verificationCode);
                break;
        }
    }

    private void confirmationModification(final String phoneNumber, String verificationCode) {
        final User user = AppProfile.getUserInfo().getUser();
        String utoken = user.getUtoken();
        if (RegexUtils.isTelPhoneNum(phoneNumber)
                && isNull(verificationCode, "验证码不能为空")) {
            LoginApi loginApi = RetrofitHelper.getLoginApi();
            RetrofitHelper.subscript(loginApi.modifyPhone(utoken, phoneNumber, verificationCode), new Action1<Response>() {
                @Override
                public void call(Response response) {
                    if (response.isStatus()) {
                        user.setMobile(phoneNumber);
                        AppProfile.getUserInfo().update();
                        Intent intent = new Intent();
                        intent.putExtra(CHANGE_PHONE, phoneNumber);
                        getActivity().setResult(Activity.RESULT_OK, intent);
                        getActivity().onBackPressed();
                    }
                    ToastUtil.show(response.getMessage());
                }
            });
        } else {
            if (!RegexUtils.isTelPhoneNum(phoneNumber)) {
                ToastUtil.show("请输入正确手机号");
            }
        }
    }

    private void startCaptcha() {
        mCaptchaSecond = 60;
        isCanClickCaptcha = false;
        mTimer = new Timer();
        mTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mCaptchaSecond--;
                        if (mCaptchaSecond == 0) {
                            mTvSendCode.setText("重新发送");
                            isCanClickCaptcha = true;
                            mTimer.cancel();
                        } else {
                            mTvSendCode.setText(mCaptchaSecond + "s，重新发送");
                        }
                    }
                });
            }
        }, 1000, 1000);
    }

    private void sendVerificationCode(final String number) {
        if (RegexUtils.isTelPhoneNum(number)) {
            if (isCanClickCaptcha) {
                LoginApi loginApi = RetrofitHelper.getLoginApi();
                RetrofitHelper.subscript(loginApi.getCaptcha(number), new Action1<Response>() {
                    @Override
                    public void call(Response response) {
                        if (response.isStatus()) {
                            startCaptcha();
                        }
                        ToastUtil.show(response.getMessage());
                    }
                });
            }
        } else {
            ToastUtil.show("请输入正确的手机号");
        }
    }

    private boolean isNull(String code, String massage) {
        if (TextUtils.isEmpty(code)) {
            ToastUtil.show(massage);
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mTimer != null) {
            mTimer.cancel();
        }
    }
}
